package org.example.config.gaud;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class AmapGeocoder {

    private static final String API_KEY = "53c90a235c7bda17b79fad57231b51bd"; // 替换为你的高德地图API Key

    /**
     * 通过高德地图API获取地址的经纬度。
     *
     * @param address 地址字符串
     * @return 包含经纬度的Map对象，如果获取失败返回null
     */
    public static Map<String, String> getGeocoder(String address) {
        try {
            String encodedAddress = URLEncoder.encode(address, StandardCharsets.UTF_8.toString());
            String urlString = "https://restapi.amap.com/v3/geocode/geo?key=" + API_KEY +
                    "&address=" + encodedAddress + "&output=json";

            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder content = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            // 打印API返回的内容，便于调试
            System.out.println("API Response: " + content.toString());

            // 解析JSON响应
            Map<String, String> result = parseJsonResponse(content.toString());
            return result;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析高德地图API返回的JSON字符串。
     *
     * @param response JSON响应字符串
     * @return 包含经纬度的Map对象
     */
    private static Map<String, String> parseJsonResponse(String response) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(response);

            int status = rootNode.get("status").asInt();
            if (status == 1) {
                JsonNode geocodes = rootNode.get("geocodes");
                if (geocodes.isArray() && geocodes.size() > 0) {
                    JsonNode firstGeocode = geocodes.get(0);
                    String location = firstGeocode.get("location").asText();
                    String[] coordinates = location.split(",");
                    if (coordinates.length == 2) {
                        Map<String, String> result = new HashMap<>();
                        result.put("lat", coordinates[1]);
                        result.put("lng", coordinates[0]);
                        return result;
                    }
                }
            } else {
                System.out.println("API 返回状态码不是 1，可能是请求失败：" + status);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            Map<String, String> json = AmapGeocoder.getGeocoder("河南省新乡市卫辉市");
            if (json != null) {
                System.out.println("lng : " + json.get("lng"));
                System.out.println("lat : " + json.get("lat"));
            } else {
                System.out.println("未获取到地理坐标信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
